package com.chao.controller;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class TestSendMsgCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/callback")
    public void TestSendMsgCallback() throws InterruptedException {
        // 1、创建回调对象 添加回调confirmCallback
        CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());
        cd.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {
            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("消息回调失败 throwable = " + throwable);
            }

            @Override
            public void onSuccess(CorrelationData.Confirm confirm) {
                System.out.println("收到confirm callback回执 ");
                if (confirm.isAck()) {
                    // 消息发送成功
                    System.out.println("消息发送成功  = 收到ack");
                } else {
                    // 消息发送失败
                    System.out.println("消息发送失败  = 收到ack 原因：。。。后面重发消息");
                }
            }
        });

        // 发送消息
        rabbitTemplate.convertAndSend("cg.direct.callback", "one", "你好mq,要给我回消息哦", cd);

        // 睡 才能看到消息
        Thread.sleep(2000);
    }
}
